看似過著四天連假的生活,其實你已規劃好一連串的旅遊。但車票只有3種:1、7、30天通行票,怎樣才能最省呢!?
使用動態規劃法,
class Solution {
public:
int mincostTickets(vector<int>& days, vector<int>& costs) {
vector<int> dp(days.back() + 1, 0);
for (int i = 1, j = 0; i <= dp.size()-1; i++) {
if (i == days[j]) {
// moving j to the next number
j++;
comparsion
dp[i] = min({
costs[0] + dp[i - 1],
costs[1] + dp[i - min(i, 7)],
costs[2] + dp[i - min(i, 30)], });
}
else {
dp[i] = dp[i - 1];
}
}
return dp.back();
}
};